#include "searchwindow.hpp"
#include "ui_search.h"
#include "common.hpp"

SearchWindow::SearchWindow(Task task, QWidget *parent):QDialog(parent), fs(task.d), 
													   er(&fs, &this->task.flist, &files), 
													   search(&fs, &files, task.k, &hits)
{
	state = Ready;
	this->task = task;
	ui = new Ui_Search;
	ui->setupUi(this);
	doc.setPlainText(task.toString() + "\n");
	ui->text->setDocument(&doc);
	ui->progress->setFormat("Ready");

	QObject::connect(ui->run, SIGNAL(clicked()), this, SLOT(runPressed()));
	QObject::connect(&er, SIGNAL(finished()), this, SLOT(enumerated()));
	QObject::connect(&search, SIGNAL(finished()), this, SLOT(searched()));
	QObject::connect(&search, SIGNAL(fileSearched(int)), this, SLOT(updateProgress(int)));
	QObject::connect(&search, SIGNAL(hitFound(Hit*)), this, SLOT(addHit(Hit*)));

	setAttribute(Qt::WA_DeleteOnClose);
}

void SearchWindow::enumerated()
{
	ui->progress->setRange(0, files.size() - 1);
	ui->progress->setFormat("Searching... %v of %m");
	ui->progress->repaint();
	search.start(QThread::IdlePriority);
}

void SearchWindow::updateProgress(int pos)
{
	log("SearchWindow: updateProgress\n");
	ui->progress->setValue(pos);
}

void SearchWindow::addHit(Hit* hit)
{
	log("SearchWindow: add Hit\n");
	QTextCursor cursor(&doc);
	cursor.movePosition(QTextCursor::End);
	cursor.insertText(hit->toString());
}

void SearchWindow::searched()
{
	log("SearchWindow: searched\n");
	state = Finished;
	ui->progress->setFormat("Search finished.");
	ui->progress->repaint();
}

void SearchWindow::runPressed()
{
	switch(state){

	case Ready:
		state = Working;
		ui->run->setEnabled(false);
		er.start(QThread::IdlePriority);
		ui->progress->setFormat("Enumerating...");
		ui->progress->repaint();
		break;

	default:
		break;
	}
}


SearchWindow::~SearchWindow()
{
	if(search.isRunning())
		search.terminate();
	if(er.isRunning())
		er.terminate();
	delete ui;
}
